#include "DatabaseManager.h"
#include <QtSql/QSqlError>
#include <QDebug>

DatabaseManager& DatabaseManager::instance()
{
    static DatabaseManager instance;
    return instance;
}

ConnectionPool* DatabaseManager::pool(const QString& name)
{
    QMutexLocker lock( & m_poolMutex); // 线程安全访问
    return m_pools.value(name, nullptr);  // 返回连接池指针（不存在时返回nullptr）
}

bool DatabaseManager::hasPool(const QString& poolName)
{
    return m_pools.find(poolName) != m_pools.end();
}

DatabaseManager::DatabaseManager(QObject* parent) : QObject(parent) {}

DatabaseManager::~DatabaseManager()
{
    QMutexLocker lock( & m_poolMutex);
    qDeleteAll(m_pools);
    m_pools.clear();
}

void DatabaseManager::addDatabase(const QString& poolName)
{
    ConnectionPool* pool = new ConnectionPool(this);

    if (m_pools.contains(poolName))
    {
        qWarning() << "Database Pool" << poolName << "already exists!";
        return;
    }
    // 配置基础参数
    pool->initialize(); // 假设已有初始化方法

    m_pools.insert(poolName, pool);
    qInfo() << "Database pool initialized:" << poolName;

}

void DatabaseManager::removeDatabase(const QString& poolName)
{
    QMutexLocker lock( & m_poolMutex);
    if (m_pools.contains(poolName))
    {
        delete m_pools.take(poolName);
        qInfo() << "Removed database pool:" << poolName;
    }
}

QSqlDatabase DatabaseManager::connection(const QString& poolName)
{
    QMutexLocker lock( & m_poolMutex);
    if (!m_pools.contains(poolName))
    {
        throw std::invalid_argument("Database pool not found: " + poolName.toStdString());
    }
    return m_pools[poolName]->getConnection();
}

void DatabaseManager::releaseConnection(QSqlDatabase conn)
{
    const QString poolName = conn.connectionName().split('_').first();
    QMutexLocker lock( & m_poolMutex);
    if (m_pools.contains(poolName))
    {
        m_pools[poolName]->releaseConnection(conn);
    }
}

// 事务管理
bool DatabaseManager::transaction(const QString& poolName)
{
    QSqlDatabase db = connection(poolName);
    bool result = db.transaction();
    releaseConnection(db);
    return result;
}

bool DatabaseManager::commit(const QString& poolName)
{
    QSqlDatabase db = connection(poolName);
    bool result = db.commit();
    releaseConnection(db);
    return result;
}

bool DatabaseManager::rollback(const QString& poolName)
{
    QSqlDatabase db = connection(poolName);
    bool result = db.rollback();
    releaseConnection(db);
    return result;
}

// 监控接口
int DatabaseManager::activeConnections(const QString& poolName) const
{
    QMutexLocker lock( & m_poolMutex);
    return m_pools.value(poolName)->activeConnections();
}

int DatabaseManager::idleConnections(const QString& poolName) const
{
    QMutexLocker lock( & m_poolMutex);
    auto pool = m_pools.value(poolName, nullptr);
    return pool ? pool->idleConnections() : -1; // 处理空指针
}

QStringList DatabaseManager::availablePools() const
{
    return m_pools.keys();
}
